package com.whut.security.browser;

import com.whut.controller.LoginController;
import com.whut.dao.UserRepository;
import org.hibernate.procedure.spi.ParameterRegistrationImplementor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * Created by WSJ on 2017/11/22.
 */
//在注册的时候就对密码进行编码，这里只是为了演示
@Component
public class MyUserDetailsService implements UserDetailsService {

    //这里可以注入dao对象
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;

    //该方法校验用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("登录用户名：" + username);
        //第二个参数应该是从数据库里面根据username取出来的经过加密的密码
        if ("admin".equals(username)){
            User user1 = new User(username,passwordEncoder.encode("root"),true,true,true,true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
            return user1;
        }else {
            com.whut.domain.User trueUser = userRepository.findUserByUserName(username);
            User user2 = new User(username,trueUser.getPassWord(),true,true,true,true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
            return user2;
        }
    }
}
